package com.sunzm.dynamic_rule.utils;

import com.alibaba.fastjson.JSON;
import com.sunzm.dynamic_rule.pojo.RuleCanalBean;
import com.sunzm.dynamic_rule.pojo.RuleParam;
import com.sunzm.dynamic_rule.pojo.RuleTableRecord;
import org.apache.flink.api.common.state.BroadcastState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @date 2021-07-19 1:49
 */
public class RuleOperationHandler2 {
    private static final Logger logger = LoggerFactory.getLogger(RuleOperationHandler2.class);

    /**
     * 规则操作处理入口方法
     *
     * @param ruleCanalBean
     * @param mapState
     */
    public static boolean handleRuleOper(RuleCanalBean ruleCanalBean,
                                         BroadcastState<String, RuleParam> mapState) {

        try {
            // 从canal信息中，取到规则表的行数据List（id,规则名,规则代码,cntsql,seqsql)
            List<RuleTableRecord> dataList = ruleCanalBean.getData();
            if (dataList == null || dataList.size() < 1) {
                return true;
            }

            // 从行数据List中取到第一行（其实就只有一行）（id,规则名,规则代码,cntsql,seqsql)
            RuleTableRecord ruleTableRecord = dataList.get(0);
            String ruleName = ruleTableRecord.getRule_name();

            // 如果status=1，则做新增规则的操作
            if (ruleTableRecord.getRule_status() == 1) {

                // status =1 表示，有一条规则要使用，则往state中插入该规则信息

                // 往statebean中放规则
                 /*
             * 本实现中的规则代码如下：
             *
 * {
    "userActionSequenceParams":[
        {
            "eventId":"addCart",
            "originEnd":9223372036854775807,
            "originStart":0,
            "rangeEnd":9223372036854775807,
            "rangeStart":0,
            "realCount":0,
            "threshold":0
        },
        {
            "eventId":"collect",
            "originEnd":9223372036854775807,
            "originStart":0,
            "rangeEnd":9223372036854775807,
            "rangeStart":0,
            "realCount":0,
            "threshold":0
        }
    ],
    "userProfileParam":{
        "sex":"1"
    },
    "ruleName":"rule2",
    "triggerParam":{
        "eventId":"addCart"
    },
    "userActionCountParams":[
        {
            "countQuerySql":"select\n    deviceId,\n    count(1) as cnt\nfrom event_detail\nwhere deviceId = ? and eventId = 'addCart' and properties['sex']='1'\n  and timeStamp between ? and ?\ngroup by deviceId",
            "eventId":"addCart",
            "originEnd":9223372036854775807,
            "originStart":0,
            "rangeEnd":9223372036854775807,
            "rangeStart":0,
            "realCount":0,
            "threshold":3
        }
    ]
}
 */
                RuleParam ruleParam = JSON.parseObject(ruleTableRecord.getRule_code(), RuleParam.class);

                //序列类规则的SQL直接从MySQL获取
                ruleParam.setActionSequenceQuerySql(ruleTableRecord.getSeq_sqls());

                // 把statebean放入state
                mapState.put(ruleName, ruleParam);

            }
            // 否则，只有删除这种情况，则做删除操作
            else {
                mapState.remove(ruleName);
            }
            return true;
        } catch (Exception e) {

            logger.error("规则处理出现异常,异常信息: \n {}", e.getMessage());

            return false;
        }
    }
}
